package HttpServlet;

import Entity.DataDTO3;
import Entity.userinformation;

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class joinmessage {
    public joinmessage(){

    }
    //绑定
    public static void join_message(DataDTO3 dataDTO3, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //读取文件中的内容
        FileInputStream fid = null;
        BufferedReader bufferedReader = null;
        int check_flag = 1;
        try {
            fid = new FileInputStream("src/main/LOGIN.txt");
            bufferedReader = new BufferedReader(new InputStreamReader(fid));

        } catch (FileNotFoundException e) {
            response.sendRedirect("/error.html");
        }
        String line = null;
        StringBuffer buf = new StringBuffer();
        Jsonb jsonb = JsonbBuilder.create();
        while ((line = bufferedReader.readLine()) != null)
        {
            userinformation personDTO = jsonb.fromJson(line, userinformation.class);
            if(personDTO.getStu_number().equals(dataDTO3.getUsername()))
            {
                check_flag = 0;
                HttpSession session = request.getSession(true);
                Map<String,String> map = new HashMap<String,String>();
                map.put("用户名",personDTO.getUsername());
                map.put("密码",personDTO.getPassword());
                map.put("学号",personDTO.getStu_number());
                map.put("手机号码",personDTO.getPhonenumber());
                map.put("电子邮箱",personDTO.getEmail());
                //HttpSession session = request.getSession(true);
                session.setAttribute("userName", map);
                session.setAttribute("token", "not null");
            }
            buf.append(line + '\n');
        }
        BufferedWriter out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream("src/main/LOGIN.txt")));

        } catch (Exception e) {
            response.sendRedirect("/error.html");
        }
        if(check_flag == 1)
        {
            userinformation personDTO = new userinformation(dataDTO3.getUsername(),"123456",dataDTO3.getUsername(),"","");
            String str = jsonb.toJson(personDTO);
            buf.append(str + '\n');
        }
        out.write(buf.toString());
        try {
            out.close();
        } catch (IOException e) {
            response.sendRedirect("/error.html");
        }
        response.sendRedirect("/show.jsp");
    }
}
